package com.gaohc.framework.web.exception;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.gaohc.common.core.domain.AjaxJson;
import com.gaohc.common.exception.BusinessException;
import com.gaohc.common.exception.DemoModeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理 
 */
@Slf4j
@ControllerAdvice
public class GlobalException {

	// 全局异常拦截（拦截项目中的所有异常）
	@ResponseBody
	@ExceptionHandler
	public AjaxJson handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) {
		// 打印堆栈，以供调试
		log.error("全局异常---------------", e);
		// 不同异常返回不同状态码
		AjaxJson aj;
		if (e instanceof NotLoginException) {	// 如果是未登录异常
			NotLoginException ee = (NotLoginException) e;
			aj = AjaxJson.getNotLogin().setMsg(ee.getMessage());
		} 
		else if(e instanceof NotRoleException) {		// 如果是角色异常
			NotRoleException ee = (NotRoleException) e;
			aj = AjaxJson.getNotJur("无此角色：" + ee.getRole());
		} 
		else if(e instanceof NotPermissionException) {	// 如果是权限异常
			NotPermissionException ee = (NotPermissionException) e;
			aj = AjaxJson.getNotJur("无此权限：" + ee.getCode());
		} else if(e instanceof DisableLoginException) {	// 如果是被封禁异常
			DisableLoginException ee = (DisableLoginException) e;
			aj = AjaxJson.getNotJur("账号被封禁：" + ee.getDisableTime() + "秒后解封");
		} else if (e instanceof MethodArgumentNotValidException) {
			MethodArgumentNotValidException ee = (MethodArgumentNotValidException) e;
			aj = AjaxJson.getNotJur("参数校验不通过：" + ee.getMessage() );
		}else if (e instanceof HttpMessageConversionException) {
			HttpMessageConversionException ee = (HttpMessageConversionException) e;
			aj = AjaxJson.getNotJur("请求类型错误：" + ee.getMessage() );
		} else if (e instanceof BindException) {
			BindException ee = (BindException) e;
			aj = AjaxJson.getNotJur("参数验证不通过：" + ee.getAllErrors().get(0).getDefaultMessage() );
		} else if (e instanceof DemoModeException) {
			DemoModeException ee = (DemoModeException) e;
			aj = AjaxJson.getNotJur("演示模式， 不允许操作");
		}else if (e instanceof BusinessException){
//			业务异常抛出
			BusinessException ee = (BusinessException) e;
			aj = AjaxJson.get(ee.getCode(), ee.getMsg());
		} else {	// 普通异常, 输出：500 + 异常信息
			aj = AjaxJson.getError(e.getMessage());
		}
		// 返回给前端
		return aj;
	}
	
}
